# coding: utf-8
import time

import UploadSurvey as us
from fralog.FraLog import Fralog
import hashlib
from settings import *
from flask import request, make_response, Response

import datetime
from dateutil.relativedelta import relativedelta

LOG = Fralog().getFileLog()


def md5(text):
    if not isinstance(text, str):
        raise Exception('Type not correct')
    m = hashlib.md5()
    m.update(text.encode())
    return m.hexdigest()


def check_limit(code):
    """
    检查用户访问次数是否已经超限
    :param user_id: 
    :return: 
    """
    pass


def create_new_user(user, pwd, product_id='hr', company_id='', code='', limit_times=20, email='', acount_type=1):
    LOG.write_log(msg='add new user', event='add_user', product_id='bole', user=user)
    db, cient = us.get_db_client()
    pwd = md5(pwd)

    t_user = {
        'user_id': user,
        'name': user,
        'pwd': pwd,
        'status': 1,
        'acount_type': acount_type,  # 1试用 2或不存在正式
        'email': email,
        'create_date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
        'role_id': 'guest'
    }
    db.t_user.insert(t_user)

    # 添加user_product
    db.t_user_product.insert({
        'product_name': '人力资源应用',
        'user_id': user,
        'product_id': product_id,
        'company_id': company_id
    })

    # 添加用户使用次数限制
    # db.t_user_limit.insert({
    #     'cur_times': 0,
    #     'max_limit': int(limit_times),
    #     'code': code
    # })
    db.t_user_limit.update(
        {'code': code}, {'$set': {'cur_times': 0,
                                  'max_limit': int(limit_times),
                                  'code': code, 'company_id': company_id
                                  }},
        upsert=True
    )


def get_pay_onlie(user, plan_no, channel_no, guid, amount=0, add_month=0):
    LOG.write_log(msg='在线支付接口 t_pay_order', user=user, plan_no=plan_no, channel_no=channel_no, product='insure',
                  amount=amount, add_month=add_month, guid=guid)
    '''
        根据方案编号获取支付信息，记录支付记录并调用微信支付接口
        记录支付订单记录
        调用微信支付接口
    '''
    try:
        timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        order_no = timestr+channel_no+guid
        db.t_pay_order.insert({'user_id': user, 'plan_no': plan_no,
                               'channel_no': channel_no,
                               'order_no': order_no,
                               'status': 0,
                               'product': 'insure',
                               'total_amount': amount,
                               'add_month': add_month,
                               'start_time': time.strftime('%Y-%m-%d %H:%M:%S',
                                                           time.localtime(time.time()))})
    except Exception as e:
        order_no = None
        LOG.error(e)
    return order_no


def get_pay_update(user, order_no, channel_no, acount_type, month):
    LOG.write_log(msg='在线支付接口 t_pay_order', user=user, order_no=order_no, channel_no=channel_no, product='insure')
    '''
        根据方案编号获取支付信息，记录支付记录并调用微信支付接口
        记录支付订单记录
        调用微信支付接口
    '''
    res = 0
    try:
        user_limit = db.t_user_limit.find_one({'user_id': user})
        if user_limit is not None:
            dead_date = user_limit.get('dead_line')
            deadline = datetime.datetime.strptime(str(dead_date), '%Y-%m-%d')
        if deadline is not None and deadline is not '':
            if acount_type == 1:
                deadline = datetime.date.today()
        dead_line = deadline + relativedelta(months=+month)
        detester = dead_line.strftime('%Y-%m-%d')
        limit = db.t_user_limit.update(
            {'user_id': user, 'product_id': 'insure'}, {'$set': {
                'dead_line': detester,
                'last_update': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            }},
            upsert=False
        )
        LOG.debug('日期更新成功！')
        if limit is not None:
            db.t_pay_order.update(
                {'user_id': user, 'order_no': order_no, 'channel_no': channel_no}, {'$set': {
                    'status': 1,
                    'dead_line': detester,
                    'last_update': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                }},
                upsert=False
            )
            if acount_type is 1:
                db.t_user.update(
                    {'user_id': user, 'channel_no': channel_no}, {'$set': {
                        'acount_type': 2,
                        'last_update': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    }},
                    upsert=False
                )
        res = 1
    except Exception as e:
        LOG.debug('支付回调系统异常！')
        LOG.error(e)
    return res


def create_add_insure_user(user, pwd, code, company_id, limit_times=10, phone='', product_id='insure',
                           email='', acount_type=2):
    LOG.write_log(msg='根据邀请码增加企业用户 add new user', event='add_user', product_id='insure', user=user, phone=phone)
    '''
        保险经纪人根据邀请码增加企业用户
        增加账号，增加 user_limit 表数据
    '''
    # 判断用户是否存在
    if check_new_user_product(user=user, product_id=product_id) > 0:
        return False
    db, cient = us.get_db_client()
    pwd = md5(pwd)

    db.t_user.update(
        {'user_id': user}, {'$set': {'user_id': user, 'name': user,
                                     'pwd': pwd,
                                     'status': 1,
                                     'phone': int(phone),
                                     'acount_type': acount_type,  # 1试用 2或不存在正式  - 保险经纪人，暂时没有试用账号
                                     'email': email,
                                     'create_date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
                                     'role_id': 'guest'
                                     }},
        upsert=True
    )
    # 添加user_product
    db.t_user_product.update(
        {'product_id': product_id, 'user_id': user}, {'$set': {'product_name': '保险经纪人项目',
                                                               'user_id': user,
                                                               'product_id': product_id,
                                                               'company_id': company_id
                                                               }},
        upsert=True
    )
    # 添加用户使用次数限制
    # db.t_user_limit.insert({
    #     'cur_times': 0,
    #     'max_limit': int(limit_times),
    #     'code': code
    # })
    dead_line = None
    # threeDayAgo = (datetime.datetime.now() + datetime.timedelta(days=30))
    # timeStamp = int(time.mktime(threeDayAgo.timetuple()))
    # 自然月
    db.t_user_limit.update(
        {'company_id': company_id,
         'product_id': product_id,
         'user_id': user, 'code': code}, {'$set': {'cur_times': 0,
                                                   'max_limit': int(
                                                       limit_times),
                                                   'code': code,
                                                   'user_id': user,
                                                   'dead_line': datetime.date.today() + relativedelta(months=+1),
                                                   'product_id': product_id,
                                                   'company_id': company_id
                                                   }},
        upsert=True
    )
    return True


def create_new_insure_user(user, pwd, code, company_id, limit_times=200, phone='', product_id='insure',
                           email='', acount_type=1, channel_no=''):
    LOG.write_log(msg='保险经纪人新增用户 add new user', event='add_user', product_id='insure', user=user, phone=phone)
    '''
        保险经纪人项目中新增账号
        增加账号，增加 user_limit 表数据
    '''

    res = False
    # 判断用户是否存在
    if check_new_user_product(user=user, product_id=product_id) > 0:
        return False
    db, cient = us.get_db_client()

    pwd = md5(pwd)
    # t_user = {
    #     'user_id': user,
    #     'name': user,
    #     'pwd': pwd,
    #     'status': 1,
    #     'acount_type': '2',  # 1试用 2或不存在正式  - 保险经纪人，暂时没有试用账号
    #     'email': email,
    #     'create_date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
    #     'role_id': 'guest'
    # }
    # db.t_user.insert(t_user)
    try:
        # 添加用户使用次数限制
        # db.t_user_limit.insert({
        #     'cur_times': 0,
        #     'max_limit': int(limit_times),
        #     'code': code
        # })
        #
        a = datetime.date.today() + relativedelta(months=+1)
        print(a)
        db.t_user_limit.update(
            {'company_id': company_id,
             'product_id': product_id,
             'user_id': user, 'code': code}, {'$set': {'cur_times': 0,
                                                       'max_limit': int(
                                                           limit_times),
                                                       'code': code,
                                                       'channel_no': channel_no,
                                                       'user_id': user,
                                                       'dead_line': str(a),
                                                       'product_id': product_id,
                                                       'company_id': company_id,
                                                       'create_date': time.strftime('%Y-%m-%d %H:%M:%S',
                                                                                    time.localtime(
                                                                                        time.time()))
                                                       }},
            upsert=True)

        db.company_collection.update(
            {'guid': company_id, 'tel': user}, {'$set': {'company_name': company_id,
                                                         'status': 1,
                                                         'guid': company_id,
                                                         'channel_no': channel_no,
                                                         'email': email,
                                                         'jobposition': 'insure',
                                                         'bd': 'insure'
                                                         }},
            upsert=True
        )

        db.t_user.update(
            {'user_id': user}, {'$set': {'user_id': user, 'name': user,
                                         'pwd': pwd,
                                         'status': 1,
                                         'channel_no': channel_no,
                                         'phone': int(phone),
                                         'acount_type': acount_type,  # 1试用 2或不存在正式  - 保险经纪人，
                                         'email': email,
                                         'create_date': time.strftime('%Y-%m-%d %H:%M:%S',
                                                                      time.localtime(time.time())),
                                         'role_id': 'guest'
                                         }},
            upsert=True
        )

        # 添加user_product
        db.t_user_product.update(
            {'product_id': product_id, 'user_id': user}, {'$set': {'product_name': '保险经纪人项目',
                                                                   'user_id': user,
                                                                   'product_id': product_id,
                                                                   'company_id': company_id,
                                                                   'channel_no': channel_no
                                                                   }},
            upsert=True
        )
        company = 'BXJJR'
        company_job = db.t_company_job.find_one({"company_id": company})
        if company_job is not None:
            percent = company_job['percent']
            db.t_company_job.update({'guid': company_id}, {'$set': {'email': email,
                                                                    'company_id': company_id,
                                                                    'p_company_id': company_id,
                                                                    'percent': percent,
                                                                    'job_name': company_id,
                                                                    'job_cname': company_id,
                                                                    'code': code,
                                                                    'create_date': time.strftime(
                                                                        '%Y-%m-%d %H:%M:%S',
                                                                        time.localtime(
                                                                            time.time()))
                                                                    }},

                                    upsert=True
                                    )
        rows = db.t_selectrule_map.find({'company_id': company})
        if rows.count() > 0:
            for item in rows:
                db.t_selectrule_map.update({'company_id': company_id, 'rule_id': item['rule_name']}, {'$set': {
                    'company_id': company_id,
                    'rule_name': item['rule_name'],
                    'rule_id': item['rule_id'],
                    'description': item['description'],
                    'ploar_type': item['ploar_type'],
                    'number': item['number'],
                    'default_select': item['default_select']}}, upsert=True)

        res = True
    except Exception as e:
        res = False
    return res


def create_new_subuser(user, md5pwd, product_id='hr', company_id='', p_company='zhongjin', limit_times=500, email='',
                       acount_type=1):
    LOG.write_log(msg='add new sub user', event='add_subuser', product_id='hr', user=user)
    if check_new_user(user) > 0:
        return False
    db, cient = us.get_db_client()
    # pwd = md5(pwd)
    pwd = md5pwd.lower()
    t_user = {
        'user_id': user,
        'name': user,
        'pwd': pwd,
        'status': 1,
        'acount_type': acount_type,  # 1试用 2或不存在正式
        'email': email,
        'p_company_id': p_company,
        'create_date': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
        'role_id': 'guest'
    }
    db.t_user.insert(t_user)
    # 添加user_product
    db.t_user_product.insert({
        'product_name': '人力资源应用',
        'user_id': user,
        'product_id': product_id,
        'p_company_id': p_company,
        'company_id': company_id
    })

    # db.t_user_limit.update(
    #     {'code': code}, {'$set': {'cur_times': 0,
    #                               'max_limit': int(limit_times),
    #                               'code': code,
    #                               'p_company_id': p_company
    #                               }},
    #     upsert=True
    # )
    return True


def check_new_user_product(user, product_id):
    db, cient = us.get_db_client()
    t_user_product = {
        'user_id': user,
        'product_id': product_id
    }
    return db.t_user_product.find(t_user_product).count()


def check_new_channel_product(channel_no, product_id):
    db, cient = us.get_db_client()
    channel_info = {
        'channel_no': channel_no,
        'product_id': product_id
    }
    return db.t_channel_info.find(channel_info).count()


def check_new_surveys_collection(company_id):
    db, cient = us.get_db_client()
    surveys_collection = {
        'company_id': company_id
    }
    return db.surveys_collection.find(surveys_collection).count()


def find_company(company):
    db, cient = us.get_db_client()
    t_company_job = {
        'company_id': company
    }
    return db.t_company_job.find(t_company_job)


def check_new_company(company):
    db, cient = us.get_db_client()
    t_company_job = {
        'company_id': company
    }
    return db.t_company_job.find(t_company_job).count()


def check_new_user(user):
    db, cient = us.get_db_client()
    t_user = {
        'user_id': user
    }
    return db.t_user.find(t_user).count()


@app.route('/account/<user>/<pwd>/<product>/<company>/<code>/<limits>', methods=['GET', 'POST'])
def create_account(user, pwd, product, company, code, limits):
    '''
      新增账号
    :param user:
    :param pwd:
    :param product:
    :param company:
    :param code:
    :param limits:
    :return:
    '''
    ret = deepcopy(g_ret)
    create_new_user(user, pwd, product, company, code, limits)
    ret['code'] = 200
    return json.dumps(ret)


@app.route('/account/create_insure_newsubaccount', methods=['GET', 'POST'])
def create_insure_subaccount():
    '''
       保险经纪人项目新增子账号
       创建t_user
       t_user_projduct
       t_user_limit
    :return:
    '''
    log.debug('保险经纪人项目insure接口调用创建用户子公司账号')
    value = get_param(request)
    user = value.get('user')
    pwd = value.get('pwd')
    code = value.get('code')
    company_id = value.get('company_id')
    product = 'insure'
    company = user
    sub_phone = user
    flag = create_new_insure_user(user=user, pwd=pwd, code=code, product_id=product, company_id=company,
                                  phone=sub_phone)
    ret = deepcopy(g_ret)
    if flag:
        ret['code'] = 200
        ret['msg'] = '创建成功！'
        ret['msg_flag'] = 'success'
        return json.dumps(ret)
    else:
        ret['code'] = 404
        ret['msg'] = '用户名重复！'
        ret['msg_flag'] = 'userid is duplication'
    return json.dumps(ret)


@app.route('/account/create_newsubaccount', methods=['GET', 'POST'])
def create_subaccount():
    # user, pwd, product, company, code, limits
    # Pincn and zhongjin
    log.debug('api接口调用创建用户子公司账号')
    value = get_param(request)
    if value.get('token') != 'tokenhuayuanapi':
        return json.dumps(g_ret)
    del value['token']
    user = value.get('user')
    pwd = value.get('pwd')
    product = value.get('product')
    company = value.get('company_id')
    code = value.get('code')
    limits = value.get('limits')
    p_company = value.get('p_company_id')
    if p_company is None:
        return g_ret
    else:
        flag = create_new_subuser(user=user, md5pwd=pwd, product_id=product, company_id=company,
                                  p_company=p_company, limit_times=limits)
    ret = deepcopy(g_ret)
    if flag:
        ret['code'] = 200
        return json.dumps(ret)
    else:
        ret['code'] = 404
        ret['msg'] = '用户名重复'
        ret['msg_flag'] = 'userid is duplication'
    return json.dumps(ret)


if __name__ == '__main__':
    # print(md5('123456'))
    # create_new_user(user='fanzq', pwd='123456', product_id='hr', company_id='zhuoyued', code='zhuoyuehrs', limit_times=20)
    # create_new_user(user='zhanghy', pwd='123456', product_id='hr', company_id='zhuoyued', code='zhuoyuehrd', limit_times=20)
    # import pypinyin
    # from pypinyin import lazy_pinyin, Style
    # job_cname = '过    加 '
    # job_cname = ''.join(lazy_pinyin(job_cname, style=Style.NORMAL)).replace(' ', '')\
    #            .replace('\t', '').replace('?', '').replace('\r', '').replace('\n', '') \
    #            .replace('/', '').replace('\\', '').replace('\r', '').replace('\n', '') \
    #            .replace('#', '').replace('&', '').replace('_', '').replace('-', '')
    # job_name = job_cname + create_4random_pwd(codelen=6)
    # code = job_name
    # print(job_cname)
    # print(job_name)
    # print(code)

    db, cient = us.get_db_client()
    # limit_list = db.t_user_limit.find({})
    # for item in limit_list:
    #     code = item.get('code')
    #     company_id = None
    #     job_item = db.t_company_job.find_one({'code': code})
    #     if job_item is not None and job_item.get('company_id') is not None:
    #         company_id = job_item.get('company_id')
    #         db.t_user_limit.update({'code': code}, {'$set': {'company_id': company_id, 'product_id': 'hr'}}, upsert=True)
    #     else:
    #         survey_item = db.surveys_collection.find_one({'code': code})
    #         if survey_item is not None and survey_item.get('company_id') is not None:
    #             company_id = survey_item.get('company_id')
    #             company_item = db.company_collection.find_one({'guid': company_id})
    #             if company_item is not None:
    #                 db.t_user_limit.update({'code': code}, {'$set': {'company_id': company_id, 'product_id': 'hr'}},
    #                                        upsert=True)
    #             else:
    #                 company2_item = db.company_collection.find_one({'company_name': company_id})
    #                 if company2_item is not None:
    #                     company_id = company2_item.get('guid')
    #                     db.t_user_limit.update({'code': code}, {'$set': {'company_id': company_id, 'product_id': 'hr'}},
    #                                            upsert=True)
